package com.scisoft.scan.control.delivery;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.scisoft.scan.control.CommonAdapter;
import com.scisoft.scan.control.CommonViewHolder;
import com.scisoft.scan.dy.R;
import com.scisoft.scan.data.delivery.DeliveryBean;
import com.scisoft.scan.data.delivery.DeliveryOrderBean;
import com.scisoft.scan.util.CommonUtil;
import com.scisoft.scan.ws.WebServiceHelper_Delivery;

import java.util.ArrayList;
import java.util.List;

public class DeliveryOrderActivity extends Activity {

    private ImageView iv_Back; //返回按钮
    private TextView tv_count;
    private TextView tv_title;
    private TextView tv_depotName;
    private TextView tv_address;
    private TextView tv_telephone;
    private TextView tv_submit;
    private TextView tv_ok;//发运按钮
    private TextView bt_undo;
    private TextView bt_done;
    private View v_undo;
    private View v_done;
    private String flag;// 1 未发 2 发运中 3 已发运，从主界面带过来
    private String bizId;// 1 已选择订单 2 未选择订单
    private List<DeliveryOrderBean> deliveryOrderBeanList = new ArrayList<>();
    private int selectDeliveryOrderCount = 0;
    private DeliveryBean deliveryBean;

    //列表
    DeliveryOrderAdapter deliveryOrderAdapter;
    private RecyclerView mRecyclerView;
    private LinearLayoutManager mLayoutManager;
    float lastY = 0;

    @SuppressLint("ClickableViewAccessibility")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);//remove title bar  即隐藏标题栏
        setContentView(R.layout.activity_delivery_order);

        //参数传递
        Intent intent = getIntent();
        //客户信息
        deliveryBean = (DeliveryBean) intent.getSerializableExtra("data");
        flag= (String) intent.getSerializableExtra("flag");
        //控件初始化
        tv_title = findViewById(R.id.tv_title);
        tv_title.setText(deliveryBean.customer);
        tv_depotName = findViewById(R.id.tv_depotName);
        tv_depotName.setText(deliveryBean.depotName);
        tv_address = findViewById(R.id.tv_address);
        tv_address.setText(deliveryBean.address);
        tv_telephone = findViewById(R.id.tv_telephone);
        tv_telephone.setText(deliveryBean.contact + "（  " + deliveryBean.telephone + "）");
        tv_count = findViewById(R.id.tv_count);
        TextView tv_title = findViewById(R.id.tv_title);
        TextView tv_address = findViewById(R.id.tv_address);
        TextView tv_telephone = findViewById(R.id.tv_telephone);
        tv_title.setText(deliveryBean.customer);
        tv_address.setText(deliveryBean.address);
        tv_telephone.setText(deliveryBean.telephone);
        //返回
        iv_Back = findViewById(R.id.iv_back);
        iv_Back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(DeliveryOrderActivity.this, DeliveryActivity.class);
                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(intent);
            }
        });

        bt_undo = findViewById(R.id.bt_undo);
        bt_done = findViewById(R.id.bt_done);
        v_undo = findViewById(R.id.v_undo);
        v_done = findViewById(R.id.v_done);
        //页签切换
        bt_undo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                setButton(v);
            }
        });
        bt_done.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                setButton(v);
            }
        });
        //提交
        tv_submit = findViewById(R.id.tv_submit);
        tv_submit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(DeliveryOrderActivity.this, LogisticsActivity.class);
                intent.putExtra("flag", flag);
                intent.putExtra("deliveryBean", deliveryBean);
                startActivity(intent);
            }
        });
        //发运
        tv_ok = findViewById(R.id.tv_ok);
        tv_ok.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                CommonUtil.showPress(DeliveryOrderActivity.this);
                CommitTask commitTask = new CommitTask(DeliveryOrderActivity.this);
                commitTask.execute();
            }
        });

        //列表适配器
        mRecyclerView = findViewById(R.id.lv_data);
        deliveryOrderAdapter = new DeliveryOrderAdapter(DeliveryOrderActivity.this);
        deliveryOrderAdapter.setMultiPage(false);
        DisplayMetrics displayMetrics = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
        int fullWidth = displayMetrics.widthPixels;
        deliveryOrderAdapter.setItemLayout(R.layout.item_deliveryorder, R.id.hsv, R.id.layout_show, R.id.layout_hide, fullWidth);
        deliveryOrderAdapter.setOnItemClickListener(new DeliveryOrderAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                if (position >= 0 && position < deliveryOrderBeanList.size()) {
                    DeliveryOrderBean bean = deliveryOrderBeanList.get(position);
                    if(bean!=null){
                        Intent intent = new Intent(DeliveryOrderActivity.this, DeliveryOrderDetailActivity.class);
                        intent.putExtra("data", bean.orderId);
                        startActivity(intent);
                    }
                }
            }
        });
        mLayoutManager = new LinearLayoutManager(this);
        mRecyclerView.setLayoutManager(mLayoutManager);
        mRecyclerView.setItemAnimator(new DefaultItemAnimator());
        //滚动的时候清空左滑按钮
        mRecyclerView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_UP:
                        if (Math.abs(event.getY() - lastY) > 5)
                            deliveryOrderAdapter.clearLeftMenuList();
                }
                return false;
            }
        });
        mRecyclerView.setAdapter(deliveryOrderAdapter);

        //初始化
        bizId = "1";//已选择的订单
        v_undo.setVisibility(View.INVISIBLE);
        v_done.setVisibility(View.VISIBLE);
        bt_undo.setTextColor(getResources().getColor(R.color.tab_text_color_unselect));
        bt_done.setTextColor(getResources().getColor(R.color.tab_text_color_select));
        CommonUtil.showPress(DeliveryOrderActivity.this);
        CreateDeliveryTask createDeliveryTask = new CreateDeliveryTask(DeliveryOrderActivity.this);
        createDeliveryTask.execute();

    }

    //设置tab页的颜色
    private void setButton(View v) {
        if (v.getId() == bt_undo.getId()) {
            bizId = "2";//未选择的订单
            v_undo.setVisibility(View.VISIBLE);
            v_done.setVisibility(View.INVISIBLE);
            bt_undo.setTextColor(getResources().getColor(R.color.tab_text_color_select));
            bt_done.setTextColor(getResources().getColor(R.color.tab_text_color_unselect));
        } else {
            bizId = "1";//已选择的订单
            v_undo.setVisibility(View.INVISIBLE);
            v_done.setVisibility(View.VISIBLE);
            bt_undo.setTextColor(getResources().getColor(R.color.tab_text_color_unselect));
            bt_done.setTextColor(getResources().getColor(R.color.tab_text_color_select));
        }
        QueryData();
    }

    //查询订单
    private void QueryData() {
        CommonUtil.showPress(DeliveryOrderActivity.this);
        QueryDeliveryTask queryDeliveryTask = new QueryDeliveryTask(DeliveryOrderActivity.this);
        queryDeliveryTask.execute();
    }

    //绑定数据
    private void BindData(Context context) {
        //数据
        deliveryOrderAdapter.clearLeftMenuList();
        deliveryOrderAdapter.clearAddItem(deliveryOrderBeanList);
        tv_count.setText("已选" + String.valueOf(selectDeliveryOrderCount) + "张订单");
    }

    //创建订单服务
    private class CreateDeliveryTask extends AsyncTask<String, Integer, String> {
        private Context mcontext;
        private String msg = "";

        CreateDeliveryTask(Context context) {
            super();
            mcontext = context;
        }

        @Override
        protected String doInBackground(String... params) {
            //查询
            try {
                //根据主单状态判断，是否需要创建或者合并操作
                if ("1".equals(flag)) {
                    //当前是从未发运跳转过来的
                    // 1）用户没有在发的发运单，那么deliveryId为空，orderId是需要发运的订单编号，后台需要自动创建发运单并生成deliveryId，这个订单进入发运中状态。
                    // 2）用户存在在发的发运单，然后选择单独发运，那么处理逻辑同1）。
                    // 3）用户存在在发的发运单，然后选择合并发运，那么deliveryId为在发的发运单编号，orderId是需要合并的另外一个订单的编号，需要把这个orderId合并到已存在的deliveryId中。
                    if (deliveryBean.deliveryId == null || "".equals(deliveryBean.deliveryId)) {
                        //如果没有发运单号，那么创建一个
                        DeliveryBean ret = WebServiceHelper_Delivery.DELIVERY_16(deliveryBean.orderId);
                        if (ret != null) {
                            deliveryBean = ret;
                        } else {
                            msg = "创建发运单失败";
                            return msg;
                        }
                    } else {
                        //如果有发运单号，说明是合并
                        msg = WebServiceHelper_Delivery.DELIVERY_05(deliveryBean.deliveryId, deliveryBean.orderId, deliveryBean.orderNo);
                        if (!msg.contains("成功")) {
                            return msg;
                        }
                    }
                }
                //查询列表数据
                if ("1".equals(bizId)) {
                    //已选择的订单
                    deliveryOrderBeanList = WebServiceHelper_Delivery.DELIVERY_03(deliveryBean.deliveryId);
                    selectDeliveryOrderCount = deliveryOrderBeanList.size();
                } else {
                    //未选择的订单
                    deliveryOrderBeanList = WebServiceHelper_Delivery.DELIVERY_04(deliveryBean.address,deliveryBean.customerId, deliveryBean.depotId,deliveryBean.deliveryId);
                    List<DeliveryOrderBean> temp = WebServiceHelper_Delivery.DELIVERY_03(deliveryBean.deliveryId);
                    selectDeliveryOrderCount = temp.size();
                }
                msg = "成功";

            } catch (Exception e) {
                msg = e.getMessage();
                e.printStackTrace();
            }
            //将结果返回给onPostExecute方法
            return msg;
        }

        @Override
        //此方法可以在主线程改变UI
        protected void onPostExecute(String result) {
            CommonUtil.hidePress();
            if (msg.contains("成功")) {
                BindData(mcontext);
                //RefreshSelection();
            } else {
                Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_LONG).show();
            }
        }
    }

    //查询订单后台服务
    private class QueryDeliveryTask extends AsyncTask<String, Integer, String> {
        private Context mcontext;
        private String msg = "";

        QueryDeliveryTask(Context context) {
            super();
            mcontext = context;
        }

        @Override
        protected String doInBackground(String... params) {
            //查询
            try {
                //发运单判断
                if(deliveryBean==null || "".equals(deliveryBean.deliveryId)){
                    msg = "发运单号不能为空";
                    return msg;
                }
                //查询列表数据
                if ("1".equals(bizId)) {
                    //已选择的订单
                    deliveryOrderBeanList = WebServiceHelper_Delivery.DELIVERY_03(deliveryBean.deliveryId);
                    selectDeliveryOrderCount = deliveryOrderBeanList.size();
                } else {
                    //未选择的订单
                    deliveryOrderBeanList = WebServiceHelper_Delivery.DELIVERY_04(deliveryBean.address,deliveryBean.customerId, deliveryBean.depotId,deliveryBean.deliveryId);
                    List<DeliveryOrderBean> temp = WebServiceHelper_Delivery.DELIVERY_03(deliveryBean.deliveryId);
                    selectDeliveryOrderCount = temp.size();
                }
                msg = "成功";

            } catch (Exception e) {
                msg = e.getMessage();
                e.printStackTrace();
            }
            //将结果返回给onPostExecute方法
            return msg;
        }

        @Override
        //此方法可以在主线程改变UI
        protected void onPostExecute(String result) {
            CommonUtil.hidePress();
            if (msg.contains("成功")) {
                BindData(mcontext);
            } else {
                Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_LONG).show();
            }
        }
    }

    //选择或者取消选择订单服务
    class SelectOrderTask extends AsyncTask<String, Integer, String> {
        private Context mcontext;
        private String msg = "";
        private DeliveryOrderBean deliveryOrderBean;

        SelectOrderTask(Context context, DeliveryOrderBean deliveryOrderBean) {
            super();
            mcontext = context;
            this.deliveryOrderBean = deliveryOrderBean;
        }

        @Override
        protected String doInBackground(String... params) {
            //查询
            try {
                if ("1".equals(bizId)) {
                    //当前是已选订单时，需要取消选择
                    msg = WebServiceHelper_Delivery.DELIVERY_06(deliveryBean.deliveryId, deliveryOrderBean);
                } else {
                    //当前是待选订单时，需要选择
                    msg = WebServiceHelper_Delivery.DELIVERY_05(deliveryBean.deliveryId, deliveryOrderBean.orderId, deliveryOrderBean.orderNo);
                }
                //查询列表数据
                if (msg.contains("成功")) {
                    if ("1".equals(bizId)) {
                        deliveryOrderBeanList = WebServiceHelper_Delivery.DELIVERY_03(deliveryBean.deliveryId);
                    } else {
                        deliveryOrderBeanList = WebServiceHelper_Delivery.DELIVERY_04(deliveryBean.address,deliveryBean.customerId, deliveryBean.depotId,deliveryBean.deliveryId);
                    }
                }

            } catch (Exception e) {
                msg = e.getMessage();
                e.printStackTrace();
            }
            //将结果返回给onPostExecute方法
            return msg;
        }

        @Override
        //此方法可以在主线程改变UI
        protected void onPostExecute(String result) {
            CommonUtil.hidePress();
            if (msg.contains("成功")) {
                if ("1".equals(bizId)) {
                    if (deliveryOrderBeanList.size() == 0) {
                        //如果主单都没有了，那么就返回主界面
                        Intent intent = new Intent(DeliveryOrderActivity.this, DeliveryActivity.class);
                        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
                        startActivity(intent);
                    }
                }
                BindData(mcontext);
            } else {
                Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_LONG).show();
            }
        }
    }

    //发运订单服务
    class CommitTask extends AsyncTask<String, Integer, String> {
        private Context mcontext;
        private String msg = "";

        CommitTask(Context context) {
            super();
            mcontext = context;
        }

        @Override
        protected String doInBackground(String... params) {
            //查询
            try {
                //查询列表数据
                msg = WebServiceHelper_Delivery.DELIVERY_15(deliveryBean.deliveryId);

            } catch (Exception e) {
                msg = e.getMessage();
                e.printStackTrace();
            }
            //将结果返回给onPostExecute方法
            return msg;
        }

        @Override
        //此方法可以在主线程改变UI
        protected void onPostExecute(String result) {
            CommonUtil.hidePress();
            if (msg.contains("成功")) {
                Toast.makeText(getApplicationContext(), "发运成功", Toast.LENGTH_LONG).show();
                Intent intent = new Intent(DeliveryOrderActivity.this, DeliveryActivity.class);
                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(intent);
            } else {
                Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_LONG).show();
            }
        }
    }

    //适配器相关功能
    class DeliveryOrderAdapter extends CommonAdapter<DeliveryOrderBean> {

        //构造函数
        public DeliveryOrderAdapter(Context context) {
            super(context);
        }

        @Override
        public void convert(CommonViewHolder holder, final DeliveryOrderBean deliveryOrderBean, int position) {
            //获取相应索引的ItemBean对象
            final DeliveryOrderBean bean = mList.get(position);
            //单号
            TextView tv_title = holder.getView(R.id.tv_title);
            tv_title.setText(bean.orderNo);
            //订单类型
            TextView tv_type = holder.getView(R.id.tv_type);
            tv_type.setText(bean.orderType);
            //统计明细
            TextView tv_detail = holder.getView(R.id.tv_detail);
            tv_detail.setText(bean.orderInfo);
            //金额
            TextView tv_amount = holder.getView(R.id.tv_amount);
            tv_amount.setText("金额 " + bean.amount + " 元");
            //是否免运费
            TextView tv_ifFree = holder.getView(R.id.tv_ifFree);
            tv_ifFree.setText(bean.isFree);
            //是否油品
            TextView tv_IfAssembly = holder.getView(R.id.tv_IfAssembly);
            tv_IfAssembly.setText(bean.IfAssembly);

            //按钮(提交)
            TextView tv_ok = holder.getView(R.id.tv_ok);
            if("1".equals(bizId)){
                tv_ok.setText("取消");
            }else{
                tv_ok.setText("合并");
            }
            tv_ok.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    CommonUtil.showPress(DeliveryOrderActivity.this);
                    SelectOrderTask selectOrderTask = new SelectOrderTask(DeliveryOrderActivity.this, bean);
                    selectOrderTask.execute();
                }
            });
        }
    }
}
